<?php

namespace Admin\Controller;

class FinishedOrderController extends AdminbaseController {

    function _initialize() {
        parent::_initialize();
        $this->currentModel = D("FinishedOrder");
    }

    //首页
    public function index() {

        $requestMap = $this->convertRequestToMap();
        $requestMap["fo#status-neq"] = -2;
        if(!isNullOrEmpty($requestMap["fo#create_time-elt"])){
            $requestMap["fo#create_time-elt"] .= " 23:59:59";
        }
        unset($requestMap["pageSize"]);
        $users_obj= M("admin");
        $userId=$_SESSION['ADMIN_ID'];
        $user=$users_obj->where("user_id=$userId")->find();
        $requestMap["fo.enterprise_code"] = $user["enterprise_code"];
        $this->assign("begin_time", $_REQUEST["fo#create_time-egt"]);
        $this->assign("end_time", $_REQUEST["fo#create_time-elt"]);

        //分页
        $count = $this->currentModel->getListCount($requestMap);
        $pageSize = $_REQUEST["pageSize"];
        if(isNullOrEmpty($pageSize)){
            $pageSize = 50;
            $page = $this->page($count, $pageSize);
        }else{
            if($pageSize == -1){
                $page = $this->page($count, 0);
            }else{
                $page = $this->page($count, $pageSize);
            }
        }
        $this->assign('pageSize', $pageSize);

        //获取order列表
        if(isNullOrEmpty($requestMap["fo#status"])){
            $requestMap["fo#status-gt"] = '-3';
        }
        if(isNullOrEmpty($requestMap["fp#class_id-eq"])){
            $requestMap["fp#class_id-neq"] = "17";
        }
        $orderList = $this->currentModel->queryForList($page, $requestMap);

        $totalCount = sizeof($orderList);
        $totalNumber = 0;
        $totalPrice = 0;
        foreach ( $orderList as $item) {
            $totalNumber += $item["number"];
            $totalPrice += $item["total_price"];
        }

        $this->assign('totalCount', $totalCount);
        $this->assign('totalNumber', $totalNumber);
        $this->assign('totalPrice', $totalPrice);

        $this->assign("user", $user);
        $this->assign("defaultEnum", C("INVOICE_TYPE"));
        $this->assign("statusEnum", C("FINISHED_ORDER_STATUS"));
        $this->assign('orderList', $orderList);
        $this->assign("page", $page->show('Admin', $this->parameter));

        $employeeRoleArr = explode(',',$user["role"]);
        if(in_array("1",$employeeRoleArr))
            $this->assign('isAdmin', "TRUE");


        $this->display();

    }


    public function endDelivery() {

        $id = $_REQUEST["id"];
        $finishedOrder = $this->currentModel->queryById($id);
        $finisheProduct = D("FinishedProduct")->queryById($finishedOrder["finished_product_id"]);
        $sales = D("admin")->where(array('employee_id'=>$finishedOrder["employee_id"]))->find();
        $this->assign("finishedOrder", $finishedOrder);
        $this->assign("finisheProduct", $finisheProduct);
        $this->assign("sales", $sales);
        $this->assign("defaultEnum", C("INVOICE_TYPE"));
        $this->display();

    }

    public function end() {


        $id = $_REQUEST["id"];

        $finishedOrder = $this->currentModel->queryById($id);

        $finishedOrder["status"] = C("FINISHED_ORDER_STATUS.END_DELIVERY");
        $finishedOrder["delivery_number"] = $_REQUEST["deliveryNumber"];
        $finishedOrder["express_company"] = $_REQUEST["expressCompany"];
        $finishedOrder["outstock_time"] = getCurrentDate();

        $users_obj= M("admin");
        $userId=$_SESSION['ADMIN_ID'];
        $user=$users_obj->where("user_id=$userId")->find();
        $finishedOrder["delivery_id"] = $user['employee_id'];

        $this->currentModel->updateInfo($finishedOrder);

        //推送留言信息到销售
        $finishedProduct = D("FinishedProduct")->queryById($finishedOrder["finished_product_id"]);
        $sales = D("admin")->where(array('employee_id'=>$finishedOrder["employee_id"]))->find();

        $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/finishedProduct/orderList/?id=" . $finishedOrder["finished_order_id"];
        $notifyData["first"] = "成品订单已发货。发货人：" . $user["admin_name"] ."，订单号：".$finishedOrder["finished_order_no"];
        if(!isNullOrEmpty($finishedOrder["patient_name"])){
            $notifyData["first"] .= "，患者：" . $finishedOrder["patient_name"];
        }
        $notifyData["keyword1"] = $finishedProduct["name"] . ", 共 " . $finishedOrder["number"] . " 件";
        if(!isNullOrEmpty($finishedOrder["patient_name"])){
            $notifyData["keyword1"] .= ", " . $finishedOrder["patient_name"];
        }
        $notifyData["keyword2"] = "[" . $finishedOrder["delivery_type"] . "]，" . $sales["admin_name"];
        if(!isNullOrEmpty($finishedOrder["agent_name"])){
            $notifyData["keyword2"] .= "，[" . $finishedOrder["agent_name"] ."]";
        }
        $notifyData["keyword3"] = $_REQUEST["deliveryNumber"];
        if(!isNullOrEmpty($_REQUEST["expressCompany"])){
            $notifyData["keyword3"] .= " [" . $_REQUEST["expressCompany"] . "]";
        }
        $notifyData["remark"] = "订单总额：" . $finishedOrder["total_price"] . " 元";
        if(!isNullOrEmpty($finishedOrder["agent_name"])){
            $notifyData["remark"] .= "，渠道[" . $finishedOrder["agent_name"] ."]";
        }

//        $adminRoleArr = array("1","8","10");
//        $openidArray = getNotifyArr($adminRoleArr, $user["enterprise_code"]);
        $openidArray = getNotifyArrByName("endFinishedOrder", $user["enterprise_code"]);
        array_push($openidArray, $sales["openid"]);
        $openidArray = array_unique($openidArray);
        foreach ($openidArray as $openid) {
            $notifyData["openid"] = $openid;
            finishedOrderEndNotify($notifyData);
        }

        $this->success("已标记成品订单为已出库状态", U("finishedOrder/index"));

    }

    public function closeOrder() {
        $id = $_REQUEST["id"];

        $finishedOrder = $this->currentModel->queryById($id);

        $finishedOrder["status"] = -2;

        $users_obj= M("admin");
        $userId=$_SESSION['ADMIN_ID'];
        $user=$users_obj->where("user_id=$userId")->find();

        $finishedOrder["delivery_id"] = $user['employee_id'];
        $finishedOrder["outstock_time"] = getCurrentDate();
        $this->currentModel->updateInfo($finishedOrder);

        //推送留言信息到销售
        $finishedProduct = D("FinishedProduct")->queryById($finishedOrder["finished_product_id"]);
        $sales = D("admin")->where(array('employee_id'=>$finishedOrder["employee_id"]))->find();

        $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/finishedProduct/orderList/?id=" . $finishedOrder["finished_order_id"];
        $notifyData["first"] = "成品订单已关闭。操作人：" . $user["admin_name"];
        $notifyData["keyword1"] = $finishedOrder["finished_order_no"];
        $notifyData["keyword2"] = "[" . $finishedProduct["name"] . "], 共 " . $finishedOrder["number"] . " 件。订单总额：" . $finishedOrder["total_price"] . " 元";
        $notifyData["keyword3"] = $finishedOrder["create_time"];
        $notifyData["remark"] = "订单人：" . $sales["admin_name"];

//        $adminRoleArr = array("1","8","10");
//        $openidArray = getNotifyArr($adminRoleArr, $user["enterprise_code"]);
        $openidArray = getNotifyArrByName("cancelFinishedOrder", $user["enterprise_code"]);
        array_push($openidArray, $sales["openid"]);
        $openidArray = array_unique($openidArray);
        foreach ($openidArray as $openid) {
            $notifyData["openid"] = $openid;
            finishedOrderCancelNotify($notifyData);
        }

        $this->success("已标记成品订单为关闭状态", U("finishedOrder/index"));

    }

    public function getTable()
    {
        $ids = $_REQUEST["id"];
        $type = $_REQUEST["type"];
        $map['class_name'] = $type;
        $formDict = D("FormDict")->queryForList($map);

        $data = array();
        $data["header"] = array();
        $data["volume"] = array();
        $data["list"] = array();
        foreach ($formDict as $key => $value){
            array_push($data["header"], $value);
            array_push($data["volume"], $key);
        }

        $users_obj= M("admin");
        $userId=$_SESSION['ADMIN_ID'];
        $user=$users_obj->where("user_id=$userId")->find();

        //获取列表
        $list = D("FinishedOrder")->alias("fo")
            ->join("left join __ADMIN__ e on e.employee_id = fo.employee_id")
            ->join("left join __ADMIN__ ad on ad.employee_id = fo.delivery_id")
            ->join("left join __ADMIN__ pv on pv.employee_id = fo.approve_id")
            ->join("left join __FINISHED_PRODUCT__ fp on fp.finished_product_id = fo.finished_product_id")
            ->where(array('fo.enterprise_code'=>$user["enterprise_code"]))
            ->order("fo.create_time desc")
            ->field("fo.*, fp.name, e.admin_name, ad.admin_name as delivery_name, pv.admin_name as approve_name")
            ->select();

//        $ids = $_REQUEST["id"];
        $idArr = explode(',', $ids);
        $numberSum = 0;
        $totalPriceSum = 0;
        $sumName = "finished_order_no";
        $numberName = "number";
        $priceName = "total_price";
        if($type == "reporting_finished_order"){
            $sumName = "finished_order_no";
            $priceName = "total_price";

        }
        if($type == "reporting_finished_2_order"){
            $sumName = "name";
            $priceName = "sale_price";
        }

        foreach ($list as $item){
            if(in_array($item["finished_order_id"], $idArr)){
                $item["delivery_number"] = " " . $item["delivery_number"];
                $item["invoice_number"] = " " . $item["invoice_number"];
                switch ($item["status"]){
                    case '-2' :
                        $item["status"] = "已关闭";
                        break;
                    case '-1' :
                        $item["status"] = "待处理";
                        break;
                    case '1' :
                        $item["status"] = "已出库";
                        break;
                }
                array_push($data["list"], $item);
                $numberSum += $item[$numberName];
                $totalPriceSum += $item[$priceName];
            }
        }

        $newItem = $list[0];
        foreach ($newItem as $key=>$value){
            if($key == $numberName)
                $newItem[$key] = $numberSum;
            elseif($key == $priceName)
                $newItem[$key] = $totalPriceSum;
            else
                $newItem[$key] = "";
        }
        $newItem[$sumName] = "合计";
        array_push($data["list"], $newItem);

        $data["bold"] = (string)(sizeof($idArr)+2);
//        $data["red"] = (string)(sizeof($idArr)+2);
//        $fileName = "定制产品报表_".date('Ymd',time());
        $agent = $_REQUEST["agent"];
        $fileName = "分销订单报表_";
        if(!isNullOrEmpty($agent)){
            $fileName .= "_" . $agent;
        }
        $fileName .= "_" . date('Ymd',time());
        exportExcel($data, $fileName);
    }

}